package com.courseware.online.controller;

import com.courseware.online.common.BusinessException;
import com.courseware.online.common.CommonUtil;
import com.courseware.online.dto.CoursewareDTO;
import com.courseware.online.service.CoursewareService;
import com.courseware.online.vo.CoursewareDetailVO;
import com.courseware.online.vo.CoursewareVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : demos
 */
@RestController
@RequestMapping(value = "api/courseware")
public class CoursewareController {

    @Autowired
    private CoursewareService coursewareService;
    @Autowired
    private CommonUtil commonUtil;

    @PostMapping(value = "/list")
    @ResponseBody
    public ResultVO getCourseware(@RequestBody(required = false) CoursewareDTO dto) {
        return new ResultVO(coursewareService.getCoursewareByPage(dto));
    }

    @GetMapping(value = "/detail/{id}")
    @ResponseBody
    public ResultVO getCoursewareDetail(@PathVariable(name = "id") Integer id) {
        return new ResultVO(coursewareService.getCoursewareDetail(id));
    }

    @PostMapping(value = "/add")
    @ResponseBody
    public ResultVO addCourseware(@RequestBody CoursewareDetailVO vo) {
        List<CoursewareVO> vos = new ArrayList<>();
        vos.addAll(coursewareService.getCoursewareByName(vo.getName()));
        if (CollectionUtils.isEmpty(vos)) {
            if (vo.getId() != null) {
                coursewareService.updateCourseWare(vo);
            } else {
                coursewareService.addCourseware(vo);
            }
            return new ResultVO();
        } else {
            if ((vos.size() == 1 && vos.get(0).getId().equals(vo.getId()))) {
                if (vo.getId() != null) {
                    coursewareService.updateCourseWare(vo);
                } else {
                    coursewareService.addCourseware(vo);
                }
                return new ResultVO();
            } else {
                throw new BusinessException(500, "文件名已存在");
            }
        }
    }

    @DeleteMapping(value = "/delete/{id}")
    @ResponseBody
    public ResultVO delCourseware(@PathVariable(value = "id") Integer id) {
        return new ResultVO(coursewareService.delCourseware(id));
    }

    @GetMapping("/download/{name}")
    public void downloadLocal(@PathVariable(value = "name") String name, HttpServletResponse response) throws IOException {
        // 读到流中
        String path = commonUtil.getFilePath(name);
        InputStream inputStream = new FileInputStream(path);// 文件的存放路径
        response.reset();
        response.setContentType("application/octet-stream");
        String filename = new File(path).getName();
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }
}
